import { createSlice } from "@reduxjs/toolkit";
import { createAsyncThunk } from "@reduxjs/toolkit";
import * as Api from "../Api/https";

const initialState = {
  shopList: [],
  shopDetail: [],
};

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    getShangJi(state, action) {
      state.shopList = action.payload;
    },
    deleteShangJi(state, action) {
      let arr = state.shopList.filter((item:any) => item.id !== action.payload);
      state.shopList = arr
    },
    searchShangJi(state, action) {
      state.shopList = action.payload;
    },
    // 添加数据
    postShangJi(state, action) {
      let arr=[...state.shopList,action.payload]
      state.shopList = arr as any
    },
    // 修改数据
    editShangJi(state, action) {
      let arr=state.shopList.map((item:any)=>{
        if(item.id===action.payload.id){
          return action.payload
        }else{
          return item
        }
      })
      state.shopList = arr as any
    },
  },
});

export default todosSlice.reducer;
export const actions = todosSlice.actions;

// 获取数据
export const r_getShangJi = createAsyncThunk("", 
  async (_, store) => {
    const res = await Api.getTableData()
    store.dispatch(actions.getShangJi(res));
});

// 单个数据置顶
export const r_Data = createAsyncThunk("", 
  async (arr, store) => {
    store.dispatch(actions.getShangJi(arr));
});

// 删除数据
export const r_DeleteShangJi = createAsyncThunk("", 
  async (id:number, store) => {
    const res = await Api.deleteTableData(id)
    console.log(res);
    store.dispatch(actions.deleteShangJi(id));
});

// 搜索数据
export const r_searchShangJi = createAsyncThunk("", 
  async (obj, store) => {
    const res = await Api.searchData(obj)
    store.dispatch(actions.searchShangJi(res))
});

// 添加数据
export const r_postShangJi = createAsyncThunk("", 
  async (obj, store) => {
    const res = await Api.addTableData(obj)
    store.dispatch(actions.postShangJi(res))
});

// 修改数据
export const r_patchShangJi = createAsyncThunk("", 
  async (obj:any, store) => {
    const res = await Api.editTableData(obj.id,obj)
    store.dispatch(actions.editShangJi(res))
});